package cn.findviewbydream.vant.plugin;

import com.intellij.codeInsight.completion.XmlTagInsertHandler;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.impl.source.xml.XmlElementDescriptorProvider;
import com.intellij.psi.xml.XmlTag;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlTagNameProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * cn.findviewbydream
 *
 * @author 白雨浓
 * date: 2019/11/11 15:43
 * content:
 */
public class VantTagNameProvider implements XmlElementDescriptorProvider, XmlTagNameProvider {

    private static Map<String, XmlElementDescriptor> cache = new ConcurrentHashMap<>();

    @Nullable
    @Override
    public XmlElementDescriptor getDescriptor(XmlTag xmlTag) {

        if (!xmlTag.getName().startsWith("van-")) {
            return null;
        }

        XmlElementDescriptor xed = cache.get(xmlTag.getName());

        if (xed != null) {
            return xed;
        }

        VantDoc.Item item = VantDoc.newInstance().getItem(xmlTag.getName());

        if (item == null) {
            return null;
        }

        xed = new VantXmlElementDescriptor(xmlTag.getName(), xmlTag.getContainingFile());

        cache.put(xmlTag.getName(), xed);
        return xed;
    }

    @Override
    public void addTagNameVariants(List<LookupElement> list, @NotNull XmlTag xmlTag, String s) {

        if (xmlTag.getName().startsWith("van-")) {
            for (String key : VantDoc.newInstance().getMap().keySet()) {
                list.add(LookupElementBuilder.create(key).withInsertHandler(XmlTagInsertHandler.INSTANCE));
            }
        }
    }
}
